package main

import "fmt"

// ==========查找==========

// 递归法二分查找
func BinarySearchRecursive(slice *[]int, leftIndex, rightIndex, value int) {
	if leftIndex > rightIndex {
		fmt.Println(-1)
		return
	}
	middleIndex := (leftIndex + rightIndex) / 2
	if value < (*slice)[middleIndex] {
		BinarySearchRecursive(slice, leftIndex, middleIndex-1, value)
	} else if value > (*slice)[middleIndex] {
		BinarySearchRecursive(slice, middleIndex+1, rightIndex, value)
	} else {
		fmt.Println(middleIndex)
	}
}

// For循环二分查找
func BinarySearchFor(slice *[]int, value int) int {
	left, right := 0, len(*slice)-1
	var mid int
	for {
		if left > right {
			return -1
		}
		mid = (left + right) / 2
		if value < (*slice)[mid] {
			right = mid - 1
		} else if value > (*slice)[mid] {
			left = mid + 1
		} else {
			return mid
		}
	}
}

func main() {
	slice := []int{1, 3, 4, 5, 10, 20, 30}
	findValue := 5
	BinarySearchRecursive(&slice, 0, len(slice)-1, findValue)
	fmt.Println(BinarySearchFor(&slice, findValue))
}
